#
# Given a lat/lon and frztype, return an array
# from gridded data.
#
import os, sys
import datetime
import tables
import numpy as np
from matplotlib.mlab import find, prctile
from cwd.lib.utils import length, invdist

import pdb
PDB = pdb.set_trace

class MonthlyGrid(object):
    def __init__(self, lat, lon, frztype, units='m', filename=None, filepath=None):
        self.lat = lat
        self.lon = lon
        self.frztype = frztype
        self.units = units

        if filepath is None:
            import cwd.settings as settings
            filepath = settings.DATA_DIR
        if filename is None:
            filename = 'TEMP_LEVELS_MONTHLY1.h5'

        # load monthly values from big grid, 
        # this is a 5d file dimensions (year,month,lon,lat,levels) = size(num_years, 12, 43, 20, 4)
        filename = os.path.join(filepath,filename)
        hdf = tables.openFile(filename)
        DR = hdf.root.data[:]
        self.last_jday = hdf.root.lastday[0].flatten()[0] # the Julian day of they last data day
        now = datetime.datetime.now()
        self.last_day = datetime.datetime(now.year,1,1) + datetime.timedelta(days=self.last_jday-1)
        hdf.close()
        del hdf

        # Transpose array to match Matlab order
        # (levels, lat, lon, month, year) = size(4, 20, 43, 12, num_years)
        DR = DR.transpose()

        # Extract the frztype we want
        # If frztype==0 this means take the 0C surface
        DR = np.squeeze(DR[frztype]) # DR=squeeze(DR(frztype,:,:,:,:));
        DR = np.reshape(DR, (20,43,12*np.size(DR,3)), order='F') # DR=reshape(DR,20,43,12*size(DR,4));
        # inverse distance weight to specified grid
        DATA = invdist(DR,360-lon,lat)
        DATA = np.reshape(DATA, (12, DATA.size/12), order='F') # DATA=reshape(DATA,12,length(DATA)/12);

        # Convert data to feet
        if self.units == 'ft':
            DATA *= 3.280839

        self.data = DATA

if __name__ == '__main__':
    lat = 36.46
    lon = 91.3
    frztype = 0
    d = MonthlyGrid(lat,lon,frztype)
